package com.ramos.kuaixiao.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.entity.BrandInfo;
import com.ramos.kuaixiao.entity.CartInfo;
import com.ramos.kuaixiao.entity.NewCartInfo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class BrandInfoDB {
    private static String TAG = "BrandInfoDB";
    private static String TABLE_NAME = "brand";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "_id" + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                + "User_Id" + " CHAR(30)," + "Shop_Name" + " CHAR(30)," + "Barcode" + " CHAR(30)," + "Encode" + " CHAR(30)," + "Icon" + " CHAR(200)," + "Price"
                + " DOUBLE," + "Num_Box" + " INTEGER," + "Num_Single" + " INTEGER," + "Param" + " INTEGER," + "Warehouse " + " CHAR(50)," + "WarehouseId " + " CHAR(50),"
                + "StoreNum " + " INTEGER," + "CustomerId " + " CHAR(50)," + "CustomerName " + " CHAR(50)," + "HouseId " + " CHAR(50)," + "HouseName " + " CHAR(50),"
                + "ucti " + " DOUBLE," + "ucte " + " DOUBLE," + "salePriceT4 " + " DOUBLE," + "realUcti " + " DOUBLE," + "realUcte " + " DOUBLE,"
                + "tcti " + " DOUBLE," + "tcte " + " DOUBLE," + "taxRate " + " DOUBLE," + "taxAmount " + " DOUBLE," + "initPrice " + " DOUBLE," + "unitSalePrice " + " DOUBLE,"
                + "address" + " CHAR(100)," + "telphone" + " CHAR(30));";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    /* 向数据库中添加数据
    * @param name
    * @param age
    * @param sex
    * @param whichclass
    */
    public int addShop(BrandInfo brandInfo) {
        Log.d(TAG, "addShop " + App.mUserId);
        List<BrandInfo> brands = findAllShop(App.mUserId);
        if (brands.size() == 0) {
            SQLiteDatabase db = DBHelper.open();
            db.execSQL("insert into brand(User_Id,Shop_Name,Barcode,Encode,Icon,Price,Num_Box,Num_Single,Param, Warehouse, WarehouseId, StoreNum ,CustomerId, CustomerName,HouseId, HouseName" +
                            ",ucti,ucte,salePriceT4,realUcti,realUcte,tcti,tcte,taxRate,taxAmount,initPrice,unitSalePrice,address,telphone) " +
                            "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                    new Object[]{App.mUserId, brandInfo.getShop_Name(), brandInfo.getBarcode(), brandInfo.getEncode(), brandInfo.getIcon(), brandInfo.getPrice(), brandInfo.getNum_Box(), brandInfo.getNum_Single(), brandInfo.getParam()
                            , brandInfo.getWarehouse(), brandInfo.getWarehouseId(), brandInfo.getStoreNum(), brandInfo.getCustomerId(), brandInfo.getCustomerName(), brandInfo.getHouseId(), brandInfo.getHouseName()
                            , brandInfo.getUcti(), brandInfo.getUcte(), brandInfo.getSalePriceT4(), brandInfo.getRealUcti(), brandInfo.getRealUcte(), brandInfo.getTcti(), brandInfo.getTcte(), brandInfo.getTaxRate(), brandInfo.getTaxAmount(), brandInfo.getInitPrice()
                            , brandInfo.getUnitSalePrice(), brandInfo.getAddress(), brandInfo.getTelphone()});
            return 0;
        } else {
            //购物车添加多客户
            /*if (getSameCustomer(brandInfo, brands)) {*/
                if (hasShopInfo(brandInfo)) {
                    if(updateShop(brandInfo) == 0){
                        return 1;
                    } else {
                        return -1;
                    }
                } else {
                    SQLiteDatabase db1 = DBHelper.open();
                    db1.execSQL("insert into brand(User_Id,Shop_Name,Barcode,Encode,Icon,Price,Num_Box,Num_Single,Param, Warehouse, WarehouseId, StoreNum ,CustomerId, CustomerName,HouseId, HouseName" +
                                    ",ucti,ucte,salePriceT4,realUcti,realUcte,tcti,tcte,taxRate,taxAmount,initPrice,unitSalePrice,address,telphone) " +
                                    "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                            new Object[]{App.mUserId, brandInfo.getShop_Name(), brandInfo.getBarcode(), brandInfo.getEncode(), brandInfo.getIcon(), brandInfo.getPrice(), brandInfo.getNum_Box(), brandInfo.getNum_Single(), brandInfo.getParam()
                                    , brandInfo.getWarehouse(), brandInfo.getWarehouseId(), brandInfo.getStoreNum(), brandInfo.getCustomerId(), brandInfo.getCustomerName(), brandInfo.getHouseId(), brandInfo.getHouseName()
                                    , brandInfo.getUcti(), brandInfo.getUcte(), brandInfo.getSalePriceT4(), brandInfo.getRealUcti(), brandInfo.getRealUcte(), brandInfo.getTcti(), brandInfo.getTcte(), brandInfo.getTaxRate(), brandInfo.getTaxAmount(), brandInfo.getInitPrice()
                                    , brandInfo.getUnitSalePrice(), brandInfo.getAddress(), brandInfo.getTelphone()});
                    return 0;
                }
           /* } else {
                return 2;
            }*/
        }
    }


    public void deleteShop(BrandInfo brandInfo) {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("delete from brand where Shop_Name=? and User_Id=?", new Object[]{brandInfo.getShop_Name(), App.mUserId});
    }

    public void deleteAllShop() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("delete from brand where User_Id=?", new Object[]{App.mUserId});
    }

    public void deleteAllCustomerShop(String customerName) {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("delete from brand where User_Id=? and CustomerName=?", new Object[]{App.mUserId, customerName});
    }

    public void clearShopMall() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM brand");
    }

    public int updateShop(BrandInfo brandInfo) {
        int boxnum = getBoxNum(brandInfo);
        int param = brandInfo.getParam();
        int singlenum = getShopNum(brandInfo);
        int storeNum = new StoreNumDB().getStoreNum(brandInfo.getEncode(), brandInfo.getWarehouseId());
        /*if (((boxnum + brandInfo.getNum_Box()) * param + singlenum + brandInfo.getNum_Single()) > storeNum) {
            ToastUtils.show("库存不足，请重新选择！请查看购物车是否已存在此商品");
            return -1;
        } else {
            updateBoxNum(brandInfo);
            SQLiteDatabase db = DBHelper.open();
            db.execSQL("update brand set Num_Single = ? where Shop_Name=? and User_Id =? and Barcode=?",
                    new Object[]{singlenum + brandInfo.getNum_Single(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()});
            return 0;
        }*/
        //允许库存不足下单
        updateBoxNum(brandInfo);
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("update brand set Num_Single = ? where Shop_Name=? and User_Id =? and Barcode=?",
                new Object[]{singlenum + brandInfo.getNum_Single(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()});
        return 0;
    }

    private void updateBoxNum(BrandInfo brandInfo) {
        int boxnum = getBoxNum(brandInfo);
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("update brand set Num_Box=? where Shop_Name=? and User_Id =? and Barcode=?",
                new Object[]{boxnum + brandInfo.getNum_Box(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()});
    }

    public void modifyShop(BrandInfo brandInfo) {
        modifyBoxNum(brandInfo);
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("update brand set Num_Single = ? where Shop_Name = ? and User_Id = ? and Barcode =?",
                new Object[]{brandInfo.getNum_Single(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()
                        });
        SQLiteDatabase db1 = DBHelper.open();
        db1.execSQL("update brand set  ucti = ?  where Shop_Name = ? and User_Id = ? and Barcode = ? ",
                new Object[]{String.valueOf(brandInfo.getUcti()), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()
                });
        SQLiteDatabase db2 = DBHelper.open();
        db2.execSQL("update brand set  ucte = ?  where Shop_Name = ? and User_Id = ? and Barcode = ? ",
                new Object[]{brandInfo.getUcte() , brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()
                });
        SQLiteDatabase db3 = DBHelper.open();
        db3.execSQL("update brand set  salePriceT4 = ? where Shop_Name = ? and User_Id = ? and Barcode = ? ",
                new Object[]{brandInfo.getSalePriceT4(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()
                });
        SQLiteDatabase db4 = DBHelper.open();
        db4.execSQL("update brand set  realUcti = ? where Shop_Name = ? and User_Id = ? and Barcode = ? ",
                new Object[]{brandInfo.getRealUcti(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()
                });
        SQLiteDatabase db5 = DBHelper.open();
        db5.execSQL("update brand set  realUcte = ?  where Shop_Name = ? and User_Id = ? and Barcode = ? ",
                new Object[]{brandInfo.getRealUcte(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()
                });
        SQLiteDatabase db6 = DBHelper.open();
        db6.execSQL("update brand set   tcti = ?  where Shop_Name = ? and User_Id = ? and Barcode = ? ",
                new Object[]{brandInfo.getTcti(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()
                });
        SQLiteDatabase db7 = DBHelper.open();
        db7.execSQL("update brand set   tcte = ? where Shop_Name = ? and User_Id = ? and Barcode = ? ",
                new Object[]{brandInfo.getTcte(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()
                });
        SQLiteDatabase db8 = DBHelper.open();
        db8.execSQL("update brand set  taxAmount = ? where Shop_Name = ? and User_Id = ? and Barcode = ? ",
                new Object[]{brandInfo.getTaxAmount(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()
                });
    }

    private void modifyBoxNum(BrandInfo brandInfo) {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("update brand set Num_Box=? where Shop_Name=? and User_Id =? and Barcode=?",
                new Object[]{brandInfo.getNum_Box(), brandInfo.getShop_Name(), App.mUserId, brandInfo.getBarcode()});
    }


    public boolean hasShopInfo(BrandInfo brandInfo) {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from brand where User_Id =? and Shop_Name=? and Barcode=?", new String[]{App.mUserId, brandInfo.getShop_Name(), brandInfo.getBarcode()});
        if (cursor.getCount() > 0) {
            cursor.close();
            Log.d(TAG, "hasCustomer true");
            return true;
        } else {
            Log.d(TAG, "hasCustomer false");
            cursor.close();
            return false;
        }
    }

    public int getBoxNum(BrandInfo brandInfo) {
        int i = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from brand where User_Id =? and Shop_Name=? and Barcode=?", new String[]{App.mUserId, brandInfo.getShop_Name(), brandInfo.getBarcode()});
        if (cursor.getCount() > 0) {
            cursor.moveToNext();
            Log.d(TAG, "getBoxNum " + cursor.getInt(7) + " " + cursor.getInt(8));
            i = cursor.getInt(7);
        }
        cursor.close();
        return i;
    }

    public int getShopNum(BrandInfo brandInfo) {
        int i = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from brand where User_Id =? and Shop_Name=? and Barcode=?", new String[]{App.mUserId, brandInfo.getShop_Name(), brandInfo.getBarcode()});
        if (cursor.getCount() > 0) {
            cursor.moveToNext();
            Log.d(TAG, "getShopNum " + cursor.getInt(7) + " " + cursor.getInt(8));
            i = cursor.getInt(8);
        }
        cursor.close();
        return i;
    }

    public List<BrandInfo> findAllShop(String userId) {
        Log.d(TAG, "userId " + userId);
        SQLiteDatabase db = DBHelper.open();
        List<BrandInfo> list = new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from brand where User_Id =?", new String[]{App.mUserId});
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            BrandInfo info = new BrandInfo();
            info.setShopChecked(true);
            info.setShop_Name(cursor.getString(2));
            info.setBarcode(cursor.getString(3));
            info.setEncode(cursor.getString(4));
            info.setIcon(cursor.getString(5));
            info.setPrice(cursor.getDouble(6));
            info.setNum_Box(cursor.getInt(7));
            info.setNum_Single(cursor.getInt(8));
            info.setParam(cursor.getInt(9));
            info.setWarehouse(cursor.getString(10));
            info.setWarehouseId(cursor.getString(11));
            info.setStoreNum(cursor.getInt(12));
            info.setCustomerId(cursor.getString(13));
            info.setCustomerName(cursor.getString(14));
            info.setHouseId(cursor.getString(15));
            info.setHouseName(cursor.getString(16));
            info.setUcti(cursor.getDouble(17));
            info.setUcte(cursor.getDouble(18));
            info.setSalePriceT4(cursor.getDouble(19));
            info.setRealUcti(cursor.getDouble(20));
            info.setRealUcte(cursor.getDouble(21));
            info.setTcti(cursor.getDouble(22));
            info.setTcte(cursor.getDouble(23));
            info.setTaxRate(cursor.getDouble(24));
            info.setTaxAmount(cursor.getDouble(25));
            info.setInitPrice(cursor.getDouble(26));
            info.setUnitSalePrice(cursor.getDouble(27));
            info.setAddress(cursor.getString(28));
            info.setTelphone(cursor.getString(29));
            Log.d(TAG, "setStoreNum " + cursor.getInt(12));
            list.add(info);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "list " + list.size());
        return list;
    }

    public List<BrandInfo> findAllCustomerShop(String userId) {
        Log.d(TAG, "userId " + userId);
        SQLiteDatabase db = DBHelper.open();
        List<BrandInfo> list = new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from brand where User_Id =? and CustomerName=?", new String[]{App.mUserId, App.selectName});
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            BrandInfo info = new BrandInfo();
            info.setShopChecked(true);
            info.setShop_Name(cursor.getString(2));
            info.setBarcode(cursor.getString(3));
            info.setEncode(cursor.getString(4));
            info.setIcon(cursor.getString(5));
            info.setPrice(cursor.getDouble(6));
            info.setNum_Box(cursor.getInt(7));
            info.setNum_Single(cursor.getInt(8));
            info.setParam(cursor.getInt(9));
            info.setWarehouse(cursor.getString(10));
            info.setWarehouseId(cursor.getString(11));
            info.setStoreNum(cursor.getInt(12));
            info.setCustomerId(cursor.getString(13));
            info.setCustomerName(cursor.getString(14));
            info.setHouseId(cursor.getString(15));
            info.setHouseName(cursor.getString(16));
            info.setUcti(cursor.getDouble(17));
            info.setUcte(cursor.getDouble(18));
            info.setSalePriceT4(cursor.getDouble(19));
            info.setRealUcti(cursor.getDouble(20));
            info.setRealUcte(cursor.getDouble(21));
            info.setTcti(cursor.getDouble(22));
            info.setTcte(cursor.getDouble(23));
            info.setTaxRate(cursor.getDouble(24));
            info.setTaxAmount(cursor.getDouble(25));
            info.setInitPrice(cursor.getDouble(26));
            info.setUnitSalePrice(cursor.getDouble(27));
            info.setAddress(cursor.getString(28));
            info.setTelphone(cursor.getString(29));
            Log.d(TAG, "setStoreNum " + cursor.getInt(12));
            list.add(info);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "list " + list.size());
        return list;
    }

    public List<BrandInfo> findAllCustomerShop(String userId,String CustomerName) {
        Log.d(TAG, "userId " + userId);
        SQLiteDatabase db = DBHelper.open();
        List<BrandInfo> list = new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from brand where User_Id =? and CustomerName=?", new String[]{App.mUserId, CustomerName});
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            BrandInfo info = new BrandInfo();
            info.setShopChecked(true);
            info.setShop_Name(cursor.getString(2));
            info.setBarcode(cursor.getString(3));
            info.setEncode(cursor.getString(4));
            info.setIcon(cursor.getString(5));
            info.setPrice(cursor.getDouble(6));
            info.setNum_Box(cursor.getInt(7));
            info.setNum_Single(cursor.getInt(8));
            info.setParam(cursor.getInt(9));
            info.setWarehouse(cursor.getString(10));
            info.setWarehouseId(cursor.getString(11));
            info.setStoreNum(cursor.getInt(12));
            info.setCustomerId(cursor.getString(13));
            info.setCustomerName(cursor.getString(14));
            info.setHouseId(cursor.getString(15));
            info.setHouseName(cursor.getString(16));
            info.setUcti(cursor.getDouble(17));
            info.setUcte(cursor.getDouble(18));
            info.setSalePriceT4(cursor.getDouble(19));
            info.setRealUcti(cursor.getDouble(20));
            info.setRealUcte(cursor.getDouble(21));
            info.setTcti(cursor.getDouble(22));
            info.setTcte(cursor.getDouble(23));
            info.setTaxRate(cursor.getDouble(24));
            info.setTaxAmount(cursor.getDouble(25));
            info.setInitPrice(cursor.getDouble(26));
            info.setUnitSalePrice(cursor.getDouble(27));
            info.setAddress(cursor.getString(28));
            info.setTelphone(cursor.getString(29));
            Log.d(TAG, "setStoreNum " + cursor.getInt(12));
            list.add(info);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "list " + list.size());
        return list;
    }

    public List<CartInfo> getAllCart(List<BrandInfo> list) {
        List<CartInfo> shops = new ArrayList<>();
        Set<String> wareHorse = new HashSet<>();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                wareHorse.add(list.get(i).getWarehouse());
            }
        }
        Log.d(TAG, "wareHorse " + wareHorse.size());
        if (wareHorse.size() > 0) {
            for (String ware : wareHorse) {
                CartInfo cartInfo = new CartInfo();
                Log.d(TAG, "wareHorse " + ware);
                cartInfo.setWarehouse(ware);
                List<BrandInfo> brandList = getCartList(ware, list);
                cartInfo.setBrandInfos(brandList);
                cartInfo.setStoreNum(brandList.size());
                cartInfo.setPrice(getAllMoney(brandList));
                shops.add(cartInfo);
            }
        }
        Log.d(TAG, "shops " + shops.size());
        return shops;
    }

    private List<BrandInfo> getCartList(String next, List<BrandInfo> list) {
        List<BrandInfo> brandList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getWarehouse().equals(next)) {
                brandList.add(list.get(i));
            }
        }
        Log.d("getCartList", "brandList.size() : " + brandList.size());
        return brandList;
    }

    public double getAllMoney(List<BrandInfo> list) {
        double allMoney = 0.0;
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                allMoney += list.get(i).getPrice() * (list.get(i).getNum_Box() * list.get(i).getParam() + list.get(i).getNum_Single());
                Log.d(TAG, "SendOrder list.get(i).getPrice()" + list.get(i).getPrice());
            }
        }
        Log.d(TAG, "SendOrder allMoney " + allMoney);
        return allMoney;
    }

    public List<NewCartInfo> getAllNewCart(List<BrandInfo> list) {
        List<NewCartInfo> shops = new ArrayList<>();
        Set<String> customers = new HashSet<>();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                customers.add(list.get(i).getCustomerName());
            }
        }
        Log.d(TAG, "customers " + customers.size());
        if (customers.size() > 0) {
            for (String customer : customers) {
                NewCartInfo cartInfo = new NewCartInfo();
                cartInfo.setCustomerName(customer);//customer名称
                List<BrandInfo> brandList = new ArrayList<>();
                brandList.clear();
                for(BrandInfo brand : list){
                    if(brand.getCustomerName().equals(customer)){
                        brandList.add(brand);
                    }
                }
                Log.d(TAG, "brandList " + brandList.size());
                cartInfo.setStoreNum(brandList.size());//customer商品数量
                cartInfo.setPrice(getAllMoney(brandList));
                Set<String> wareHouses = new HashSet<>();
                if (brandList.size() > 0) {
                    for (int i = 0; i < brandList.size(); i++) {
                        wareHouses.add(brandList.get(i).getWarehouse());
                    }
                }
                //构造仓库层
                List<NewCartInfo.CartInfo> cartlist = new ArrayList<>();
                cartlist.clear();
                if(wareHouses.size() > 0){
                    for(String wareHouse : wareHouses){
                        NewCartInfo.CartInfo cart = new NewCartInfo.CartInfo();
                        cart.setWarehouse(wareHouse);

                        List<BrandInfo> brands = new ArrayList<>();
                        brands.clear();
                        for(BrandInfo brand : brandList){
                            if(brand.getWarehouse().equals(wareHouse)){
                                brands.add(brand);
                            }
                        }
                        Log.d(TAG, "wareHouses " + wareHouses.size());
                        cart.setStoreNum(brands.size());
                        cart.setPrice(getAllMoney(brands));
                        cart.setBrandInfos(brands);
                        cartlist.add(cart);
                    }
                }

                cartInfo.setList(cartlist);

                shops.add(cartInfo);
            }
        }
        Log.d(TAG, "shops " + shops.size());
        return shops;
    }
}
